import * as globalObj from './proto_lib';

var isSocketOpen=false;
var lastHeartBeatTime=0;
cc.Class({
    extends: cc.Component,

    properties: {
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        //先默认建立起WS
        this.connectGSWithWS();
        cc.game.addPersistRootNode(this.node);
		
		//初始化时间
		globalObj.initTime();

    },

    update (dt) {
        //遍历消息队列
        globalObj.checkMsgList(this);

        //定时心跳60秒
        if(isSocketOpen){
            lastHeartBeatTime+=dt;
            if(lastHeartBeatTime>=60){
                globalObj.send([10003]);
                lastHeartBeatTime=0;
            }
        };

        globalObj.update(dt);
    },

    sc_role_heart_beat(msgData){
        //todo
		globalObj.setServerTime(msgData[0]);
    },

    reconnect(){
        this.connectGSWithWS();
    },

    //和GS建立websocket
    connectGSWithWS: function () {
        var ws = new WebSocket("ws://129.28.165.228:8002");
        globalObj.globalws = ws;
        ws.onopen = function (event) {
            console.log("WS was opened.");
            isSocketOpen=true;
        };
        ws.onmessage = function (event) {
            var Msg = JSON.parse(event.data);
            var protoData = Msg[1];
            //整理格式，存入消息队列
            globalObj.msgList.push({msgID:protoData[0],msgData:protoData[1]});
        };
        ws.onerror = function (event) {
            console.log("WebSocket fired an error");
            isSocketOpen=false;
            //将异常信息，加入消息列表让其他节点获取
            globalObj.msgList.push({msgID:1,msgData:0});
        };
        ws.onclose = function (event) {
            console.log("WebSocket closed.");
            isSocketOpen=false;
            //将异常信息，加入消息列表让其他节点获取
            globalObj.msgList.push({msgID:1,msgData:0});
        };
    }
});
